package com.community.controller;

import com.community.entity.School;
import com.community.service.SchoolService;
import com.community.util.Result;
import com.community.util.Search;
import com.feng.fengDUtil.Page;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@RestController
@RequestMapping(value = "/school")
public class SchoolAction {
    @Autowired
    private SchoolService schoolService;

    @RequestMapping(value = "/list")
    public Result list(Page page, Search search) {
        schoolService.query(page,search);
        return Result.success(page);
    }


    @RequestMapping(value = "/updateSchoolVideo")
    public Result updateSchoolVideo(@RequestBody School school) {
        schoolService.updateSchoolVideo(school);
        return Result.success(school);
    }

    @RequestMapping(value = "/updateSchoolPolicy")
    public Result updateSchoolPolicy(@RequestBody School school) {
        schoolService.updateSchoolPolicy(school);
        return Result.success(school);
    }

    @RequestMapping(value="/del")
    public Result del(String ids){
        try {
            schoolService.deleteByIds(School.class,ids);
            return Result.success();
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }

    @RequestMapping(value = "/{id}")
    public Result save(@PathVariable String id) {
        return Result.success(schoolService.selectById(School.class,id));
    }

    @RequestMapping(value = "/save")
    public Result save(@RequestBody School school) {
        schoolService.saveOrUpdate(school);
        return Result.success(school);
    }


    @RequestMapping(value="/uploadImage",method= RequestMethod.POST)
    public Result uploadFile(@RequestParam("file") MultipartFile file) {
        try {
            return Result.success(schoolService.saveImage(file));
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("上传失败");
        }
    }

    @GetMapping(value = "/downloadSchools")
    public void downloadSchools(HttpServletResponse resp) throws IOException {
        Workbook wookbook = schoolService.downloadSchools();
        resp.setContentType("application/octet-stream");
        //通知浏览器下载文件而不是打开
        String fileName =  java.net.URLEncoder.encode("学校列表.xls", "UTF-8");
        resp.addHeader("Content-Disposition", "attachment; filename="+fileName);
        ServletOutputStream out = resp.getOutputStream();
        wookbook.write(out);
    }

}
